<template>
  <div :style="{ width: `${width}px`, height: `${height}px` }">
    <el-upload
      :http-request="uploadFileImgApi"
      :file-list="fileList"
      :limit="limit"
      :list-type="listType"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :auto-upload="true"
      :style="{ width: '100%', height: '100%' }"
      class="w-[150px] height-[150px]"
    >
      <el-icon>
        <Plus />
      </el-icon>
      <template #file="{ file }">
        <div class="w-full">
          <img
            class="el-upload-list__item-thumbnail w-full"
            :src="file.url"
            alt=""
          />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <el-icon>
                <ZoomIn />
              </el-icon>
            </span>
            <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleDownload(file)"
            >
              <el-icon>
                <Download />
              </el-icon>
            </span>
            <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>

    <el-dialog v-model="dialogVisible" class="image-preview-dialog">
      <div class="mt-4">
        <img
          class="preview-image w-full"
          :src="dialogImageUrl"
          alt="Preview Image"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from "vue";
import { uploadFileApi } from "@/api/system/file";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import { ElMessage } from "element-plus";
const emit = defineEmits(["update:modelValue", "change"]);
import { getFullUrl } from "@/utils/auth";

const props = defineProps({
  modelValue: {
    type: [String, Array],
    default: () => []
  },
  isView: {
    type: Boolean,
    defalut: false
  },
  limit: {
    type: Number,
    default: 1
  },
  fileTypes: {
    type: Array,
    default: () => ["image/jpeg", "image/png"]
  },
  width: {
    type: Number,
    default: 150
  },
  height: {
    type: Number,
    default: 150
  },
  maxSize: {
    type: Number,
    default: 5 // MB
  },
  listType: {
    type: String,
    default: "picture-card"
  }
});
// 图片预览相关状态和方法
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(props.isView);

// 添加自定义上传方法（假设已有封装好的http请求）
const uploadFileImgApi = async option => {
  console.log("uploadFileImgApi", option);
  const formData = new FormData();
  formData.append("file", option.file); // 文件字段
  // formData.append("directory", "user"); // 将目录参数加入FormDat
  try {
    const res = await uploadFileApi(formData); // 移除第二个参数
    option.onSuccess(res);
  } catch (err) {
    option.onError(err);
  }
};
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

const handleDownload = (file: UploadFile) => {
  console.log(file);
};
const handleChangeStart = file => {
  console.log("handleChangeStart", file);
  emit("change", file);
};

const fileList1 = computed(() => {
  if (!props.modelValue) return [];
  return Array.isArray(props.modelValue)
    ? props.modelValue.map(url => ({ url }))
    : [{ url: props.modelValue }];
});
// 新增上传逻辑
const handleSuccess1 = response => {
  console.log("handleSuccess", response);
  const newUrl = response.data.url;
  const newValue =
    props.limit === 1
      ? newUrl
      : [...props.modelValue, newUrl].slice(0, props.limit);
  emit("update:modelValue", newValue);
  emit("change", newValue);
};

// 上传前校验
const beforeUpload = file => {
  console.log("beforeUpload", file);
  const isTypeValid = props.fileTypes.includes(file.type);
  const isSizeValid = file.size / 1024 / 1024 < props.maxSize;

  if (!isTypeValid) {
    ElMessage.error(`仅支持 ${props.fileTypes.join(",")} 格式`);
    return false;
  }

  if (!isSizeValid) {
    ElMessage.error(`文件大小不能超过 ${props.maxSize}MB`);
    return false;
  }

  return true;
};

// 删除时更新数据
const handleRemove = file => {
  let newValue;
  if (props.limit === 1) {
    newValue = "";
  } else {
    newValue = (props.modelValue || []).filter(url => url !== file.url);
  }
  emit("update:modelValue", newValue);
  emit("change", newValue);
};

const fileList = computed(() => {
  if (!props.modelValue) return [];
  const urls = Array.isArray(props.modelValue)
    ? props.modelValue
    : [props.modelValue];
  const filteredUrls = urls.filter(Boolean).map(url => ({ url }));
  filteredUrls.forEach(url => {
    if (!url.url.startsWith("http")) {
      url.url = getFullUrl(url.url);
    }
  });
  return filteredUrls;
});

// handleSuccess条件判断
const handleSuccess = response => {
  const newUrl = response.data.url;
  const currentValue = Array.isArray(props.modelValue)
    ? props.modelValue
    : [props.modelValue].filter(Boolean);

  const newValue =
    props.limit === 1
      ? newUrl
      : [...currentValue, newUrl].slice(0, props.limit);

  emit("update:modelValue", newValue);
  emit("change", newValue);
};
</script>
<style scoped>
/* 隐藏超出限制的上传按钮 */
:deep(.el-upload-list__item + .el-upload) {
  display: none !important;
}

/* 统一图片预览尺寸 */
:deep(.el-upload-list__item-thumbnail) {
  width: 100% !important;
  height: 100% !important;
  object-fit: cover;
}

:deep(.el-upload-list .el-upload-list--picture-card),
:deep(.el-upload-list--picture-card) {
  width: 100% !important;
  height: 100% !important;
}

/* 调整上传按钮尺寸 */
:deep(.el-upload) {
  width: 100%;
  height: 100%;
}
</style>
<style>
.el-upload-list--picture-card .el-upload-list__item {
  width: 100% !important;
  height: 100% !important;
  margin: 0px !important;
}
</style>
